package com.cn.web.controller.bc;

import com.alibaba.fastjson2.JSONObject;

import com.cn.bean.pojo.bc.User;
import com.cn.bean.vo.bc.UserRolePermission;
import com.cn.common.utils.JwtUtils;
import com.cn.config.config.Msg;
import com.cn.config.config.Result;
import com.cn.mapper.dao.db1.bc.LoginDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;

@CrossOrigin
@RestController
public class LoginController {
    private final LoginDao loginDao;

    @Autowired
    public LoginController(LoginDao loginDao) {
        this.loginDao = loginDao;
    }
    @Autowired(required = false)
    private JwtUtils jwtUtils;

    @RequestMapping("/guest/login")
    @ResponseBody
    public Result guestLogin() {
        try {
            // 在游客登录成功后生成令牌，角色设置为"guest"
            String token = jwtUtils.getJwtTokenForGuest();
            // 将令牌返回给前端
            return Result.success("200",token);
        } catch (Exception e) {
            // 处理异常情况
            return Result.failure("500","登录失败");
        }
    }

    @RequestMapping("/login/Purposes")
    @ResponseBody
    public Msg selectPurposes(@RequestBody JSONObject jsonObject) throws UnsupportedEncodingException {
        Msg msg = new Msg();
        String userName = jsonObject.getString("userName");
        String userPassword = jsonObject.getString("userPassword");
        List<User> users = loginDao.loginIndex(userName, userPassword);
        String role = "admin";
        String token=jwtUtils.getJwtToken(userName,userPassword,role);
        if (users.isEmpty()) {
            msg.setCode(500);
            msg.setMessage("账号或密码错误");
            return msg;
        }
        if (users.get(0).getStatus()==0){
            msg.setCode(500);
            msg.setMessage("账号异常,请联系管理员");
            return msg;
        }
        msg.setCode(200);
        msg.setMessage("登录成功");
        msg.setToken(token);
        return msg;
    }

    // 获取所有权限
    @RequestMapping("/get/Permission")
    @ResponseBody
    public List<UserRolePermission> getPermission(@RequestBody JSONObject jsonObject) {
        String userName = jsonObject.getString("userName");

        return loginDao.getPermission(userName);
    }
}
